var t = getApp(),
  e = t.requirejs("core"),
  s = t.requirejs("wxParse/wxParse"),
  n = 0,
  r = [],
  d = [];
Page({
  data: {
    route: "goods_detail",//路径
    menu: t.tabBar,
    menu_show: false,
    icons: t.requirejs("icons"),
    goods: {},
    //轮播图
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    circular: true,
    advWidth: 0,  //窗口宽度
    info: "active",//默认展开商品详情
    para: "",//参数
    slider:'',
    buyType: "",
    pickerOption: {},
    specsData: [],
    specsTitle: "",
    tempname: "",//弹框
    showPicker: false,//页面阴暗效果
    total: 1,   //默认选择数量
    canBuy: true,//判断库存
    optionid:0 ,//初始规格未选中的状态。buyNow()调用
    spec_Show:true,
    button_color: t.config.button_color,
    font_color: t.config.font_color,
    config: t.config,
    display:true
  },
  to_poster:function(k){
      t.get_poster(k);
      e.jump('/yb_shop/pages/poster/index');
  },
  onGotUserInfo: function (q) {

    var that = this,
      e = t.getCache("userinfo");
    that.setData({
      display: false
    })
    if (e) {
      return;
    }
    t.getUserInfo(q.detail.userInfo, function (t) {
      if (t != 1000) {
        // that.getList();
        // that.setData({
        //   display: false
        // })
      } else {
        that.setData({
          display: true
        })
      }

    });

  },
  //底部导航跳转
  menu_url: function (k) {
    e.menu_url(k, 2);
  },
  onLoad: function (ez) {
    
    if (ez.scene) {
     var scene = decodeURIComponent(ez.scene);
      scene = scene.split(',');
      console.log(scene);
      ez.id = scene[0];
      ez.pid = scene[1];
      }

    var cache = t.getCache("userinfo");
    if (cache) {
      this.setData({
        display: false
      })
    }
    if (ez && ez.pid) {
      var name = t.get_user_name(ez.pid, this);
      this.setData({
        pid: ez.pid
      })
      t.set_share_pid(ez.pid);
      t.setCache('pid', ez.pid);
    }
    if (ez != null && ez != undefined) {
      this.setData({
        tabbar_index: ez.tabbar_index ? ez.tabbar_index : -1
      });
    }
    e.setting();
    if (this.data.tabbar_index >= 0) {
      this.setData({
        showtabbar: true,
      })
    }
    
    var a = this;
    console.log(ez)
      a.setData({
        menu: getApp().tabBar,
        page_config: getApp().page,
        options: ez,//保存商品ID
        //areas: t.getCache("cacheset").areas
        button_color: getApp().config.button_color,
        font_color: getApp().config.font_color,
        config: getApp().config
      }),
      wx.getSystemInfo({//获取系统资料
        success: function (t) {
          //console.log(t)
          a.setData({
            advWidth: t.windowWidth  //窗口宽度
          })
        }
      })
    
  },
  onShow: function () {
    var e=this.data.options;
    this.getDetail(e)
    //this.history(e)
    //this.GoodsClicks(e)
  },
  url:function(){
    var url="/yb_shop/pages/member/cart/index?key=1";
    wx.navigateTo({
      url: url,
      fail: function (i) {
          e.jump(url, 3)
      }
    })
  },
  /**
* 下拉刷新
*/
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  /**
   *访问该页面，对应商品点击量加1
   * @param goods_id
   * @return string
   */
  GoodsClicks: function (t) {
    e.get("goods/GoodsClicks", {
      goods_id: t.id
    }, function (t) {
      //console.log(t)
    })
  },
 /**
   *立即购买
   * @param goods_id sku_id uid total
   * @return url
   */
  buyNow: function (t) {
    //console.log(t)
    var i = this,
      s = i.data.optionid;
    if (i.data.goods.sku.length>1){
    if (s == 0){
      wx.showToast({
        title: '请选择规格',
        icon: 'loading',
        duration: 1000
      })
    }
    wx.redirectTo({
      url: "/yb_shop/pages/order/create/index?goods_id=" + i.data.options.id + "&total=" + i.data.total + "&sku_id=" + s + "&uid=" + getApp().getCache("userinfo").uid
    })
    }else{
      wx.redirectTo({
        url: "/yb_shop/pages/order/create/index?goods_id=" + i.data.options.id + "&total=" + i.data.total + "&sku_id=" + i.data.goods.sku['0'].sku_id + "&uid=" + getApp().getCache("userinfo").uid
      })
    }      
      
  },

  /**
   *加入购物车
   * @param goods_id sku_id buyer_id goods_name num goods_images
   * @return string
   */
  getCart: function (t) {
    var i = this,
      sku_id='',
      s = i.data.optionid;
      if (i.data.goods.sku.length > 1) {
        if (s == 0) {
          e.alert('请选择规格！')
          return;
        }
        sku_id=s
    } else {
        sku_id= i.data.goods.sku['0'].sku_id
    }

      e.get("Cart/AddCart", {
        buyer_id: getApp().getCache("userinfo").uid,
        num: i.data.total,
        sku_id: sku_id,
        goods_id: i.data.goods.goods_id,
        goods_name: i.data.goods.goods_name,
        goods_images: i.data.goods.images
      }, function (t) {
        //console.log(t)
        0 == t.code ?(
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1500
          }),
        i.setData({
          active: "",
          slider: "out",
            "goods.cart": parseInt(i.data.goods.cart) + parseInt(i.data.total)
        })
      ) : e.alert(t.msg)
      })
    
  },
 
   /**
   *点击按钮 弹出 选择规格、数量页面
   */
  selectPicker: function (t) {
    var a = this,
      o = t.currentTarget.dataset.tap,
      i = t.currentTarget.dataset.buytype;
      //console.log(o)
     a.setData({
      active: "active",
      slider: "in",
      tempname: "select-picker",
      buyType: i,
      
    })
     d = this.data.goods.sku
     //默认规格选中
     if (a.data.goods.goods_spec_format.length != 0) {
     
       a.setData({
         optionid: d['0'].sku_id,
         "goods.stock": d['0'].stock,
         "goods.promote_price": d['0'].promote_price,
         "goods.cost_price": d['0'].cost_price,
         "goods.market_price": d['0'].market_price,
         "goods.price": d['0'].price,
         "goods.sku_pic": (d['0'].pic!= null) ? d['0'].pic.img_cover:''
       }),console.log(d['0'])
         d['0'].stock <= 0 ? a.setData({
           canBuy: false
         }) : a.setData({
           canBuy: true
         })
       var r = a.data.goods.goods_spec_format,
       o = "",
       arr=[];       
       r.forEach(function (t, k) {
         arr[k] = {
           id: t.spec_id,
          vid :t.value[0].spec_value_id,
          spec_name:t.value[0].spec_value_name
          }
         o += t.value[0].spec_value_name + "， "
       }),
       a.setData({
         specsData: arr,
         specsTitle: o
       })
     }else{
       d['0'].stock <= 0 ? a.setData({
         canBuy: false
       }) : a.setData({
         canBuy: true
       })
       a.setData({
         "goods.sku_pic": (d['0'].pic != null) ? d['0'].pic.img_cover : ''
       })
     }
  },

  /**
   *选中规格后在data中储存相应的数量、价格、sku等信息
   */
  specsTap: function (t) {
    var e = this,
      o = "",
      i = "",
      a = t.target.dataset.idx;
      r = e.data.specsData;
    r[a] = {
      id: t.target.dataset.id,
      vid: t.target.dataset.vid,
      spec_name: t.target.dataset.spec_name
    };

    var choose = [];
    r.forEach(function (t) {
        o += t.spec_name + "， ";
        i = t.id+":"+t.vid;
        choose.push(i);
    });

      d.forEach(function (a) {
        var right = true;
        choose.forEach(function(vv){
          if (a.attr_value_items.indexOf(vv) < 0)
          {
            right = false;
          }
        });

        right && (e.setData({
          optionid: a.sku_id,
          "goods.stock": a.stock,
          "goods.promote_price": a.promote_price,
          "goods.cost_price": a.cost_price,
          "goods.market_price": a.market_price,
          "goods.price": a.price,
          "goods.sku_pic": (a.pic!=null) ? a.pic.img_cover : ''
        }), a.stock <= 0 ? e.setData({
          canBuy: false
        }) : e.setData({
          canBuy:true
        })
        )
      }),

      e.setData({
        specsData: r,
        specsTitle: o
      })
  },
   /**
   *改变商品数量
   */
  number: function (t) {
    var o = this,
      s=e.data(t),
      i = e.pdata(t),
      num = i.value;
    if (!t.target.dataset.action) {
      return false;
    }
    if ("minus" === s.action) {
      if (num > 1 && num > i.min) { num = num-1; }
      else { return e.toast("已是最少购买量") }
    } else if ("plus" === s.action) {
      if (num < i.max) { num = num+1; }
      else { return e.toast("最多购买" + i.max + "件") }
    }
    o.setData({
      total: num
    })
  },

  /**
   *隐藏 选选数量、规格的 弹框
   */
  emptyActive: function () {
    this.setData({
      active: "",
      slider: "out",
      //showPicker: false,
    })
  },

   /**
   *获取商品详情信息
   * @param goods_id uid
   * @return array
   */
  getDetail: function (t) {
    var a = this,
    total='';
    a.setData({
      loading: true
    }),
      e.get("goods/GoodsDetail", {
      goods_id: t.id,
      uid: getApp().getCache("userinfo").uid
      }, function (t) {
        console.log(t)
        if (t.code==0)  {
          if (t.info.sku.length == 1) {
            a.setData({
              optionid: -1
            })
          }
          if (t.info.min_buy) {
            total = t.info.min_buy
          } else {
            total = 1
          }
          var ass = t.info.description;
          s.wxParse("wxParseData", "html", t.info.description, a, "0"),
            a.setData({
              show: true,
              goods: t.info,
              total: total
            })

          wx.setNavigationBarTitle({
            title: t.info.goods_name || "商品详情"
          })
        }else{
          e.alert(t.msg)
        }
      })
  },
  
  /**
   *商品详情模块、商品属性模块切换
   * @param para  商品属性
   * @param info 商品详情
   * @return string
   */
  goodsTab: function (t) {
    var a = this,
      o = t.currentTarget.dataset.tap;
    if ("info" == o)
      this.setData({
        info: "active",
        para: "",
      });
    else if ("para" == o)
      this.setData({
        info: "",
        para: "active",
      });
  },
  
  /**
   *商品收藏
   * @param fav_id  商品id
   * @param log_price 收藏时的价格
   * @param uid 用户id
   * @return string
   */
  favorite: function (t) {
    var a = this,
      o = t.currentTarget.dataset.logprice;
    e.get("goods/Favorites", {
      fav_id: a.data.options.id,
      log_price: o,
      uid:getApp().getCache("userinfo").uid
    }, function (t) {
        0 == t.code ? (
          t.info.status == 1 ? a.setData({ //异步刷新页面
            "goods.favorites": true
          }) : a.setData({
            "goods.favorites": false
          })
        ): e.alert(t.msg)

    
    })
  },
  
  //分享
  onShareAppMessage: function () {
    
    var title = this.data.goods.goods_name,
      uid = getApp().getCache('userinfo').uid ? getApp().getCache('userinfo').uid:0;
    var path = '/yb_shop/pages/goods/detail/index?id=' + this.data.goods.goods_id + '&pid=' + uid;
    return {
      title: title,
      path: path
    }
  },
})